
//leetcode:160.相交链表


/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public int size(ListNode head) {
        int sz = 0;
        while(head!=null){
            head = head.next;
            sz++;
        }
        return sz;
    }
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA==null || headB==null) {
            return null;
        }
        //1.分别求出两个链表的长度
        int lenA = size(headA);
        int lenB = size(headB);
        //2.让较长的链表先走两个链表的长度差的步长
        ListNode curA = headA;
        ListNode curB = headB;
        if(lenA>=lenB) {
            int len = lenA-lenB;
            while(len>0) {
                curA = curA.next;
                len--;
            }
        } else {
            int len = lenB-lenA;
            while(len>0) {
                curB = curB.next;
                len--;
            }
        }
        //3.验证是否为链式结构
        while(curA!=null && curB!=null) {
            if(curA == curB) {
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return null;
    }
}